import {createSlice, createAsyncThunk} from '@reduxjs/toolkit'
import { addTodo,getTodos } from '../../api/todos'
const todosSlice = createSlice({
    name:'todos',
    initialState:{
        todos:[]
    },
    extraReducers:(builder)=>{
        builder.addCase(asyncAddTodo.fulfilled, (state, {payload})=>{
            state.todos.push(payload)
        })
        .addCase(asyncGetTodos.fulfilled, (state, {payload})=>{
            state.todos = payload
        })
    }
})

/**
 * 异步添加todo的actionCreator
 */
export const asyncAddTodo = createAsyncThunk('todos/addTodo', async (payload)=>{ // payload {title:'xxx', isDone:false}
    let todo = await addTodo(payload)
    return todo
})
/**
 * 获取todos列表
 */
export const asyncGetTodos = createAsyncThunk('todos/getTodos', async (payload)=>{
    let todos = await getTodos()
    return todos
})

export default todosSlice.reducer


